package _18_剑指OfferII;

import java.util.HashMap;
import java.util.Map;

public class _006_剑指OfferII排序数组中两个数字之和 {

    // 双指针，空间复杂度O（1）
    public int[] twoSum(int[] numbers, int target) {
        int left = 0;
        int right = numbers.length - 1;
        while (left < right) {
            int total = numbers[left] + numbers[right];
            if (total > target) right--;
            else if (total < target) left++;
            else {
                return new int[]{left, right};
            }
        }
        return null;
    }

    // 利用hash表保存数据, 需要空间复杂度
    public int[] twoSum1(int[] numbers, int target) {
        Map<Integer, Integer> map = new HashMap<>();
        map.put(numbers[0], 0);

        for (int i = 1; i < numbers.length; i++) {
            Integer index = map.get(target - numbers[i]);
            if (index != null) {
                return new int[]{index, i};
            }
            map.put(numbers[i], i);
        }
        return null;
    }

}
